package com.guigu.youxuan.controller;

import com.guigu.youxuan.common.utils.PageUtils;
import com.guigu.youxuan.pojo.BackMenu;
import com.guigu.youxuan.pojo.BackPermission;
import com.guigu.youxuan.pojo.BackRole;
import com.guigu.youxuan.pojo.BackUser;
import com.guigu.youxuan.pojo.dto.DataDto;
import com.guigu.youxuan.pojo.dto.LoginForm;
import com.guigu.youxuan.pojo.dto.LoginReturnData;
import com.guigu.youxuan.pojo.dto.MetaDto;
import com.guigu.youxuan.service.IBackMenuService;
import com.guigu.youxuan.service.IBackPermissionService;
import com.guigu.youxuan.service.IBackRoleService;
import com.guigu.youxuan.service.IBackUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liweixin
 * @since 2024-05-15
 */
@CrossOrigin
@RestController
@RequestMapping("/backUser")
public class BackUserController {

    @Autowired
    private IBackUserService backUserService;
    @Autowired
    private IBackRoleService backRoleService;
    @Autowired
    private IBackMenuService backMenuService;
    @Autowired
    private IBackPermissionService backPermissionService;

    /**
     * 删除用户
     * @param backUser
     * @return
     */
    @RequestMapping("/delBackUser")
    public String delBackUser(@RequestBody BackUser backUser) {
        backUserService.delBackUser(backUser);
        return "删除成功！";
    }

    /**
     * 批量删除用户
     * @param backUserList
     * @return
     */
    @RequestMapping("/delsBackUser")
    public String delsBackUser(@RequestBody List<BackUser> backUserList) {
        backUserService.delsBackUser(backUserList);
        return "删除成功！";
    }

    /**
     * 修改用户
     * @param backUser
     * @return
     */
    @RequestMapping("/updateBackUser")
    public String updateBackUser(@RequestBody BackUser backUser) {
        backUserService.updateBackUser(backUser);
        return "修改成功";
    }

    /**
     * 修改用户的的查询回显
     * @param userId
     * @return
     */
    @RequestMapping("/queryBackUser/{userId}")
    public BackUser queryBackUser(@PathVariable() Long userId) {
        BackUser backUser = backUserService.queryBackUser(userId);
        return backUser;
    }

    /**
     * 新增用户
     * @param backUser
     * @return
     */
    @RequestMapping("/addBackUser")
    public String addBackUser(@RequestBody BackUser backUser) {
        backUserService.addBackUser(backUser);
        return "新增员工成功！";
    }

    /**
     * 头像上传
     * @return
     */
    @RequestMapping("/avatarImgUpload")
    public String avatarImgUpload(MultipartFile file) {

        //获取源文件名(包含后缀 1.jpg)
        String originalFilename = file.getOriginalFilename();
        //截取后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成唯一文件名
        String newFileName = UUID.randomUUID().toString()+suffix;
        //该文件要放在指定目录下
        File dir = new File("D:/myimgs/staff");
        if(!dir.exists())
            dir.mkdir();
        //目标文件对象
        File destFile = new File(dir,newFileName);

        //文件写入
        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "http://localhost:10001/images/staff/"+newFileName;
    }

    /**
     * 用户禁用/启用
     * @param backUser
     * @return
     */
    @RequestMapping("/switchStatus")
    public String switchStatus(@RequestBody BackUser backUser) {
       backUserService.switchStatus(backUser);
       if (backUser.getStatus() == 0) {
           return "启用成功";
       }
        return "禁用成功";
    }

    /**
     * 用户列表查询
     * @param backUser
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/getBackUserList/{currentPage}/{pageSize}")
    public PageUtils<BackUser> getBackUserList(@RequestBody BackUser backUser,
                                               @PathVariable int currentPage,
                                               @PathVariable int pageSize) {
        PageUtils<BackUser> page = backUserService.getBackUserList(backUser,currentPage,pageSize);
        return page;
    }

    /**
     * 用户登录
     * @param loginForm
     * @return
     */
    @RequestMapping("/login")
    public LoginReturnData login(@RequestBody LoginForm loginForm) {
        LoginReturnData loginReturnData = new LoginReturnData();
        DataDto dataDto = new DataDto();
        MetaDto metaDto = new MetaDto();
        //查询当前账户是否能登录
        BackUser backUser = backUserService.getBackUser(loginForm);
        if(backUser != null) {

            //查询用户的角色
            List<BackRole> backRoleList = backRoleService.getBackRoleList(backUser.getId());

            //查询用户的菜单
            List<BackMenu> backMenuList = backMenuService.getBackMenuList(backUser.getId());

            //查询用户的权限
            List<BackPermission> backPermissionList = backPermissionService.getBackPermissionList(backUser.getId());

            //菜单分层
            List<BackMenu> finalBackMenuList = new ArrayList<>();
            //处理一级菜单及其下的子菜单
            for (BackMenu menu : backMenuList) {
                if (menu.getLevel() == 1) {
                    // 二级菜单列表
                    List<BackMenu> children = new ArrayList<>();
                    // 查找并添加二级菜单
                    for (BackMenu subMenu : backMenuList) {
                        if (subMenu.getLevel() == 2 && subMenu.getParentId().equals(menu.getId())) {
                            // 三级菜单列表
                            List<BackMenu> grandChildren = new ArrayList<>();
                            // 查找并添加三级菜单
                            for (BackMenu grandSubMenu : backMenuList) {
                                if (grandSubMenu.getLevel() == 3 && grandSubMenu.getParentId().equals(subMenu.getId())) {
                                    grandChildren.add(grandSubMenu);
                                }
                            }
                            // 设置二级菜单的子菜单
                            subMenu.setChildren(grandChildren);
                            children.add(subMenu);
                        }
                    }
                    // 设置一级菜单的子菜单
                    menu.setChildren(children);
                    // 添加到最终列表
                    finalBackMenuList.add(menu);
                }
            }

            //权限分层
            List<BackPermission> finalBackPermissionList = new ArrayList<>();
            for(BackPermission permission : backPermissionList) {
                if(permission.getLevel() == 1) {
                    //二级权限列表
                    List<BackPermission> children = new ArrayList<>();
                    //遍历全部权限
                    for(BackPermission subPermission : backPermissionList) {
                        if(subPermission.getLevel() == 2 && subPermission.getParentId().equals(permission.getId())) {
                            children.add(subPermission);
                        }
                    }
                    permission.setChildren(children);
                    finalBackPermissionList.add(permission);
                }
            }

            //封装数据
            dataDto.setUser(backUser);
            dataDto.setRolesList(backRoleList);
            dataDto.setMenuList(finalBackMenuList);
            dataDto.setPermissionList(finalBackPermissionList);
            UUID token = UUID.randomUUID();
            dataDto.setToken(token);


            metaDto.setMsg("登录成功");
            metaDto.setStatus(200);


            loginReturnData.setData(dataDto);
            loginReturnData.setMeta(metaDto);


            return loginReturnData;
        }
        metaDto.setMsg("账号或密码错误！");
        metaDto.setStatus(500);
        loginReturnData.setMeta(metaDto);
        return loginReturnData;
    }
}
